<template>
	<div>
		<el-upload
			:action="oss.action"
			:data="oss"
			list-type="picture-card"
			:file-list="fileList"
			:before-upload="beforeUpload"
			:on-remove="handleRemove"
			:on-success="handleSuccess"
			:on-preview="handlePreview"
			:limit="maxCount"
			:on-exceed="handleExceed"
		>
			<i class="el-icon-plus"></i>
		</el-upload>
		<el-dialog :visible.sync="dialog.visible">
			<img width="100%" :src="dialog.imageUrl" alt="" />
		</el-dialog>
	</div>
</template>

<script>
export default {
	data() {
		return {
			oss: {
				policy: '',
				signature: '',
				key: '',
				OSSAccessKeyId: '',
				action: '',
				success_action_status: 200
			},
			dialog: { 
				visible: false, 
				imageUrl: '' ,
			},
			files_: []
		};
	},
	props: {
		dir: {
			type: String,
			default: ''
		},
		files: {
			type: Array
		},
		maxCount: {
			type: Number,
			default: 5
		}
	},
	computed: {
		fileList: {
			get: function() {
				return this.files_;
			},
			set: function(files) {
				this.files_ = files;
			}
		}
	},
	methods: {
		emitSetList(fileList) {
			let files_ = [];
			for (let i = 0; i < fileList.length; i++) {
				files_.push(fileList[i].url);
			}
			this.$emit('setList', files_);
		},
		async beforeUpload(file) {
			let this_ = this;
			await this.$https.get('/file/getPolicyUploadInfo', { dir: this_.dir }).then(res => {
				let data = res.data.data;
				this_.oss.key = this_.dir + '/' + new Date().getTime() + file.name;
				this_.oss.policy = data.policy;
				this_.oss.OSSAccessKeyId = data.accessid;
				this_.oss.signature = data.signature;
				this_.oss.action = data.host;
			});
		},
		handleRemove(file, fileList) {
			let array = this.files_;
			this.files_.forEach((item, index, array) => {
			    if(item === file) {
			        array.splice(index, 1);
			    }
			});
			this.emitSetList(files_);
		},
		handlePreview(file) {
			this.dialog = {
				visible: true,
				imageUrl: file.url
			};
		},
		handleSuccess(res, file) {
			let url = this.oss.action + '/' + this.oss.dir + '/' + file.name;
			this.files_.push({ name: file.name, url: url });
			this.emitSetList(this.files_);
		},
		handleExceed(files, fileList) {
			this.$message({
				message: '最多只能上传' + this.maxCount + '个文件',
				type: 'warning',
				duration: 3000
			});
		}
	},
	watch: {
		'files': {
			handler() {
				let files = [];
				if (this.files) {
					for (let i = 0; i < this.files.length; i++) {
						if (this.files[i].url) {
							let fileUrl = this.files[i].url;
							let name = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
							let item = { name: name, url: fileUrl };
							files.push(item);
						}
					}
				}
				this.files_ = files;
			},
			immediate: true
		}
	}
};
</script>

<style lang="less" scoped="scoped"></style>
